package com.pfzy.liveeventbusdemo.activity

import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.Toast
import androidx.annotation.Nullable
import com.jeremyliao.liveeventbus.LiveEventBus
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.pfzy.liveeventbusdemo.LiveEventBusDemo
import com.pfzy.liveeventbusdemo.R
import com.pfzy.liveeventbusdemo.databinding.ActivityPostDelayBinding

/**
 * 延迟后
 */
class PostDelayActivity : AppCompatActivity() {
    private var binding: ActivityPostDelayBinding? = null
    // 发送计数
    private val sendCount = 1000
    // 接收计数
    private var receiveCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_post_delay)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_post_delay)
        binding?.lifecycleOwner = this
        binding?.handler = this

        LiveEventBus
            .get(KEY_TEST_DELAY_LIFE_LONG, String::class.java)
            .observe(this, object : Observer<String> {
                override fun onChanged(@Nullable s: String?) {
                    Toast.makeText(
                        this@PostDelayActivity,
                        "receiveCount: $receiveCount", Toast.LENGTH_SHORT
                    ).show()
                    receiveCount++
                }
            })
    }

    /**
     * 进程内发送消息，延迟发送
     */
    fun testDelayNoLife(view: View?) {
        LiveEventBus
            .get<String>(LiveEventBusDemo.KEY_TEST_DELAY_LIFE)
            .postDelay("Send Msg To Observer Delay 2s", 2000)
        finish()

        // 进程内发送消息，延迟发送，带生命周期
        // void postDelay(LifecycleOwner sender, T value, long delay)
    }

    fun testDelayWithLife(view: View?) {
        LiveEventBus
            .get<String>(LiveEventBusDemo.KEY_TEST_DELAY_LIFE)
            .postDelay(this, "Send Msg To Observer Delay 2s", 2000)
        finish()
    }

    fun testDelayWithLifeLast(view: View?) {
        for (i in 0 until sendCount) {
            LiveEventBus
                .get<Any>(KEY_TEST_DELAY_LIFE_LONG)
                .postDelay(this, "Send $i Msg To Observer Delay 2s", 2000)
        }
        Handler().postDelayed({
            Toast.makeText(
                this@PostDelayActivity, "sendCount: " + sendCount +
                        " | receiveCount: " + receiveCount, Toast.LENGTH_LONG
            ).show()
        }, 3000)
    }

    companion object {
        const val KEY_TEST_DELAY_LIFE_LONG = "key_test_delay_life_long"
    }
}
